import json, requests
from .utils import sign, gen_timestamp
from disn.settings import JD_APP_KEY, JD_APP_SECRET, JD_ACCESS_TOKEN

__all__ = ('JDClient',)

class JDClient(object):
    """Jingdong API Client"""

    BASE_URL = 'https://api.jd.com/routerjson'

    def __init__(self, key=JD_APP_KEY, secret=JD_APP_SECRET, token=JD_ACCESS_TOKEN):
        self.key = key
        self.secret = secret
        self.token = token

    def call(self, method, app_params=None, token=None):
        """Call specific method to fetch data returned by API.

        :param method: the method to be called.
        :param app_params: application parameters which are required
                           to call the specific method.
        :param token: call a specific method may need setup a specific token
        """
        params = {
            'method': method,
            'app_key': self.key,
            'timestamp': gen_timestamp(),
            'v': '2.0',
            '360buy_param_json': json.dumps(app_params),
        }
        if token is not None:
            params['access_token'] = token
        elif self.token is not None:
            params['access_token'] = self.token
        params['sign'] = sign(self.secret, params)
        res = requests.get(self.BASE_URL, params=params)
        # print(res.text)
        res.raise_for_status()
        return json.loads(res.content, strict=False)

    def get_promotion_code(self, materialId, channel='PC'):
        method = 'jingdong.service.promotion.getcode'
        # http_protocol = 1 if materialId and materialId.strip().startswith('https') else 0
        params = {
            'promotionType':7,
            'materialId': materialId,
            'unionId':1000277898,
            'channel':channel,
            # 'webId':'1045068090', # http
            'webId':'1562461018',
            'adtType':'6',
            'protocol':1  # 传输协议 1为https 其他为 http
        }
        res = self.call(method, params)
        obj1 = res['jingdong_service_promotion_getcode_responce']
        ret_dict = {}
        ret_dict['code'] = '0'
        ret_dict['msg']  = None
        ret_dict['url']  = None
        # print(type(obj1))
        if 'code' in obj1 and obj1['code'] == '0':
            obj2_str = obj1['queryjs_result']
            # print(type(obj2_str))
            obj2 = json.loads(obj2_str)
            # print(type(obj2))
            if 'resultCode' in obj2 and obj2['resultCode'] == '0' and 'url' in obj2:
                ret_dict['url'] = obj2['url']
            else:
                ret_dict['code'] = obj2['resultCode']
            if 'resultMessage' in obj2:
                ret_dict['msg']  = obj2['resultMessage']
        else:
            ret_dict['code'] = obj1['code']
        return(ret_dict)

